"use client";
import React, { useEffect, useRef, useState } from "react";
import { Button, Input, Upload, message, Image } from "antd";
import { SendOutlined, PictureOutlined, DeleteOutlined, ExpandOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-components";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import "./index.css";
import { chatMuitiStreamUsingPost, chatStreamUsingPost } from "@/api/dummyInterviewController";
import { UploadChangeParam } from "antd/es/upload";
import { RcFile, UploadFile } from "antd/es/upload/interface";
import { uploadFileUsingPost } from "@/api/fileController";
import path from 'path';
import fs from 'fs';

/**
 * AI 模拟面试页面
 * @constructor
 */
export default function Interview() {
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const [inputValue, setInputValue] = useState<string>("");
  const [chatHistory, setChatHistory] = useState<Array<{ role: "user" | "ai"; content: string; imageUrl?: string }>>([]);
  const [interviewId, setInterviewId] = useState<number>(0);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [currentTypingMessage, setCurrentTypingMessage] = useState<string>("");
  const [file, setFile] = useState<RcFile | null>(null);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [sentImageUrl, setSentImageUrl] = useState<string | null>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const [isTyping, setIsTyping] = useState<boolean>(false);

  // 初始化聊天室 ID
  useEffect(() => {
    // 生成一个随机的聊天室 ID
    const randomId = Math.floor(Math.random() * 1000000);
    setInterviewId(randomId);
    
    // 添加 AI 的欢迎消息
    setChatHistory([
      {
        role: "ai",
        content: "你好！我是你的 AI 面试官，请问你想面试什么岗位？",
      },
    ]);

    console.log("Interview component initialized with ID:", randomId);
  }, []);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [chatHistory, currentTypingMessage]);
  
  // 监控状态变化，便于调试
  useEffect(() => {
    console.log("Chat history updated:", chatHistory);
  }, [chatHistory]);
  
  useEffect(() => {
    console.log("Loading state:", isLoading);
  }, [isLoading]);

  // 处理图片上传
  const handleUpload = (info: UploadChangeParam<UploadFile<any>>) => {
    const { file } = info;
    console.log("图片上传组件信息:", info);
    console.log("图片上传文件对象:", file);
    
    // 验证文件是否为图片格式
    const isImageFile = file.type?.startsWith('image/');
    const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/webp'];
    
    if (!isImageFile || !validImageTypes.includes(file.type || '')) {
      message.error('请上传正确的图片格式 (JPEG, PNG, GIF, JPG, WEBP)');
      return;
    }
    
    // 处理原始文件
    try {
      let originFile: RcFile;
      
      if (file.originFileObj) {
        // 标准情况：originFileObj 存在
        originFile = file.originFileObj as RcFile;
      } else if (file instanceof File) {
        // 备选方案1：file 本身就是 File 对象
        originFile = file as unknown as RcFile;
      } else if ('uid' in file) {
        // 备选方案2：尝试直接使用 file 对象
        originFile = file as unknown as RcFile;
      } else {
        throw new Error("无法获取有效的文件对象");
      }
      
      console.log("获取到文件:", originFile.name);
      setFile(originFile);
      
      // 创建预览URL
      const previewUrl = URL.createObjectURL(originFile);
      setPreviewImage(previewUrl);
      
      message.success("图片已选择");
    } catch (error) {
      console.error("处理文件对象时出错:", error);
      message.error("图片选择失败，请重试");
    }
  };
  
  // 删除已选择的图片
  const handleRemoveImage = () => {
    if (previewImage) {
      URL.revokeObjectURL(previewImage);
    }
    setFile(null);
    setPreviewImage(null);
  };

  // 上传文件到本地服务器
  const uploadImageToServer = async (file: RcFile): Promise<{absolutePath: string, relativePath: string}> => {
    console.log("开始上传文件到服务器:", file.name);
    
    try {
      const formData = new FormData();
      formData.append('file', file);
      console.log("已创建FormData，添加了文件");

      console.log("发送请求到 /api/upload");
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      });

      console.log("收到响应:", response.status, response.statusText);
      
      if (!response.ok) {
        let errorMessage = '上传失败';
        try {
          const error = await response.json();
          errorMessage = error.error || errorMessage;
        } catch (e) {
          console.error("解析错误响应失败:", e);
        }
        console.error("上传失败:", errorMessage);
        throw new Error(errorMessage);
      }

      const data = await response.json();
      console.log("上传成功，收到响应数据:", data);
      
      if (!data.filePath || !data.relativePath) {
        console.error("响应数据缺少必要的路径信息:", data);
        throw new Error('服务器响应缺少路径信息');
      }
      
      return {
        absolutePath: data.filePath, // 返回绝对路径
        relativePath: data.relativePath // 返回相对路径用于显示
      };
    } catch (error) {
      console.error("文件上传过程中发生错误:", error);
      throw error;
    }
  };

  // 发送消息
  const handleSendMessage = async () => {
    if (!inputValue.trim() && !file) {
      message.warning("请输入消息或上传图片");
      return;
    }

    try {
      const userMessage = inputValue.trim();
      let imagePath = "";
      let imageRelativePath = "";
      let tempPreviewUrl = previewImage;
      
      console.log("准备发送消息:", userMessage, "是否有图片:", !!file);
      
      // 如果有上传图片，先上传到本地服务器
      if (file) {
        try {
          console.log("开始处理图片上传:", file.name);
          // 验证文件是否为图片格式
          const isImageFile = file.type?.startsWith('image/');
          const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/webp'];
          
          if (!isImageFile || !validImageTypes.includes(file.type || '')) {
            message.error('请上传正确的图片格式 (JPEG, PNG, GIF, JPG, WEBP)');
            return;
          }
          
          message.loading({ content: '正在上传图片...', key: 'uploading' });
          
          // 上传文件到本地服务器
          const uploadResult = await uploadImageToServer(file);
          imagePath = uploadResult.absolutePath;
          imageRelativePath = uploadResult.relativePath;
          
          message.success({ content: '图片上传成功', key: 'uploading', duration: 2 });
          console.log("图片上传成功:", {absolutePath: imagePath, relativePath: imageRelativePath});
          
          if (!imagePath) {
            message.error("图片上传失败");
            return;
          }
        } catch (error) {
          console.error("图片上传失败:", error);
          message.error({ content: '图片上传失败', key: 'uploading', duration: 2 });
          return;
        }
      }
      
      // 添加用户消息到聊天历史，包含图片URL
      console.log("添加用户消息到聊天历史:", { 
        content: userMessage || "发送了一张图片",
        imageUrl: imageRelativePath || undefined
      });
      
      setChatHistory((prev) => [
        ...prev,
        { 
          role: "user", 
          content: userMessage || "发送了一张图片",
          imageUrl: imageRelativePath || undefined
        },
      ]);
      
      // 清空输入框和预览
      setInputValue("");
      
      if (previewImage) {
        console.log("清理预览图片");
        // 在消息中使用完图片后再释放预览URL
        URL.revokeObjectURL(previewImage);
        setPreviewImage(null);
      }
      setFile(null);
      setSentImageUrl(null);
      
      setIsLoading(true);
      message.loading({ content: 'AI思考中...', key: 'ai-thinking' });
      
      // 重置当前打字内容并激活打字状态
      setCurrentTypingMessage("");
      setIsTyping(true);

      // 创建EventSource连接
      let eventSourceUrl;
      if (imagePath) {
        console.log("使用多模态API (带图片)");
        eventSourceUrl = `/api/sse?path=${encodeURIComponent("/api/dummyinterview/chatByMuitiStream")}&interviewId=${interviewId}&query=${encodeURIComponent(userMessage)}&imagePath=${encodeURIComponent(imagePath)}`;
      } else {
        console.log("使用纯文本API");
        eventSourceUrl = `/api/sse?path=${encodeURIComponent("/api/dummyinterview/chatStream")}&interviewId=${interviewId}&query=${encodeURIComponent(userMessage)}`;
      }

      console.log("创建SSE连接:", eventSourceUrl);
      
      // 创建 EventSource 连接
      const eventSource = new EventSource(eventSourceUrl);
      
      // 处理连接打开
      eventSource.onopen = () => {
        console.log("SSE连接打开成功");
        message.destroy('ai-thinking');
      };
      
      // 用于累积完整响应的变量
      let fullResponse = "";
      
      // 处理消息事件
      eventSource.onmessage = (event) => {
        if (!event.data) return;
        
        const data = event.data;
        
        if (data && data !== '[DONE]') {
          // 累加到完整响应中
          fullResponse += data;
          // 更新当前打字内容
          setCurrentTypingMessage(fullResponse);
          
          // 确保滚动到底部
          if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
          }
        }
      };

      // 处理错误
      eventSource.onerror = (error) => {
        console.error("SSE错误:", error);
        eventSource.close();
        setIsLoading(false);
        setIsTyping(false);
        message.destroy('ai-thinking');
        
        if (!fullResponse) {
          setChatHistory((prev) => [
            ...prev,
            { role: "ai", content: "抱歉，我遇到了一些问题，无法生成回答。" },
          ]);
        } else {
          // 如果已经收到了部分回复，将其添加到聊天历史
          setChatHistory((prev) => [
            ...prev,
            { role: "ai", content: fullResponse },
          ]);
          // 清空当前打字内容
          setCurrentTypingMessage("");
        }
      };

      // 监听结束事件
      eventSource.addEventListener("end", (event) => {
        console.log("收到结束事件");
        eventSource.close();
        setIsLoading(false);
        message.destroy('ai-thinking');
        
        // 打字效果完成，将完整回复添加到聊天历史
        if (fullResponse) {
          console.log("添加AI回复到聊天历史");
          setChatHistory((prev) => [...prev, { role: "ai", content: fullResponse }]);
          // 清空当前打字内容
          setCurrentTypingMessage("");
          setIsTyping(false);
        }
      });
    } catch (error: any) {
      console.error("发送消息出错:", error);
      setIsLoading(false);
      setIsTyping(false);
      message.destroy('ai-thinking');
      message.error("发送失败：" + error.message);
    }
  };

  // 处理输入框回车事件
  const handlePressEnter = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 滚动到底部的辅助函数
  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      setTimeout(() => {
        if (chatContainerRef.current) {
          chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
      }, 50);
    }
  };

  return (
    <PageContainer
      header={{
        title: "AI 模拟面试",
        ghost: true,
        subTitle: "基于先进AI技术的智能面试助手",
        extra: [
          <div key="tech-info" className="tech-info">
            <span className="tech-pulse"></span>
            AI引擎已就绪
          </div>
        ]
      }}
    >
      <div className="interview-container">
        {/* 科技风格装饰元素 */}
        <div className="tech-lines">
          <div className="tech-line"></div>
          <div className="tech-line"></div>
          <div className="tech-line"></div>
        </div>
        
        {/* 聊天历史区域 */}
        <div className="chat-container" ref={chatContainerRef}>
          {/* 聊天历史消息 */}
          {chatHistory.map((message, index) => (
            <div
              key={index}
              className={`message-bubble ${message.role === "user" ? "user-message" : "ai-message"}`}
            >
              <div className="message-avatar">
                {message.role === "user" ? (
                  <img
                    src={loginUser.userAvatar || "/assets/tech-user-avatar.svg"}
                    alt="用户头像"
                    className="avatar"
                  />
                ) : (
                  <img
                    src="/assets/tech-ai-avatar.svg"
                    alt="AI头像"
                    className="avatar"
                  />
                )}
              </div>
              <div className="message-content">
                {/* 显示用户上传的图片 */}
                {message.role === "user" && message.imageUrl && (
                  <div className="message-image-container">
                    <Image 
                      src={message.imageUrl}
                      alt="用户上传图片"
                      className="message-image"
                      preview={{
                        maskClassName: 'message-image-preview-mask',
                        mask: <div><ExpandOutlined /></div>
                      }}
                    />
                  </div>
                )}
                
                {message.content.split("\n").map((line, i) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < message.content.split("\n").length - 1 && <br />}
                  </React.Fragment>
                ))}
              </div>
            </div>
          ))}
          
          {/* 正在生成的回复 - 作为实时AI消息显示 */}
          {isTyping && currentTypingMessage && (
            <div className="message-bubble ai-message">
              <div className="message-avatar">
                <img
                  src="/assets/tech-ai-avatar.svg"
                  alt="AI头像"
                  className="avatar"
                />
              </div>
              <div className="message-content">
                {currentTypingMessage.split("\n").map((line, i) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < currentTypingMessage.split("\n").length - 1 && <br />}
                  </React.Fragment>
                ))}
                <span className="cursor-blink">|</span>
              </div>
            </div>
          )}
        </div>
        
        {/* 输入区域 - AI回答时禁用输入 */}
        <div className="input-container">
          {/* 图片预览区域 */}
          {previewImage && (
            <div className="image-preview">
              <div className="preview-wrapper">
                <Image 
                  src={previewImage} 
                  alt="预览图片" 
                  className="preview-image"
                  preview={{
                    maskClassName: 'preview-image-mask',
                    mask: <div><ExpandOutlined /></div>
                  }}
                />
                <Button
                  type="text"
                  danger
                  icon={<DeleteOutlined />}
                  className="remove-image-btn"
                  onClick={handleRemoveImage}
                />
              </div>
            </div>
          )}
          
          <Input.TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder={isLoading ? "AI正在回复中，请稍候..." : "请输入你想问的问题..."}
            autoSize={{ minRows: 1, maxRows: 4 }}
            onKeyPress={handlePressEnter}
            disabled={isLoading}
            className="tech-input"
          />
          
          <div className="input-actions">
            <Upload
              showUploadList={false}
              beforeUpload={(file) => {
                console.log("beforeUpload 被调用，文件:", file.name, "类型:", file.type);
                
                // 验证文件格式
                const isImageFile = file.type?.startsWith('image/');
                const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/webp'];
                
                if (!isImageFile || !validImageTypes.includes(file.type)) {
                  message.error('请上传正确的图片格式 (JPEG, PNG, GIF, JPG, WEBP)');
                  return Upload.LIST_IGNORE;
                }
                
                // 直接处理文件
                try {
                  console.log("直接处理文件:", file.name);
                  setFile(file);
                  const previewUrl = URL.createObjectURL(file);
                  setPreviewImage(previewUrl);
                  message.success("图片已选择");
                } catch (err) {
                  console.error("处理文件失败:", err);
                  message.error("图片选择失败，请重试");
                }
                
                return false; // 阻止自动上传，我们会在发送消息时上传
              }}
              disabled={isLoading || !!previewImage}
              accept="image/jpeg,image/png,image/gif,image/jpg,image/webp"
              maxCount={1}
            >
              <Button
                icon={<PictureOutlined />}
                type="text"
                title="上传图片"
                className="upload-button"
                disabled={isLoading || !!previewImage}
              />
            </Upload>
            
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={handleSendMessage}
              disabled={isLoading}
              className="send-button"
            >
              发送
            </Button>
          </div>
        </div>
        
        {/* 科技风格页脚 */}
        <div className="interview-footer">
          © 2025 智能面试刷题平台 | AI面试技术支持
        </div>
      </div>
    </PageContainer>
  );
}